package com.yunhe.authority.service.authority.impl;

import cn.jiguang.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunhe.authority.domain.authority.*;
import com.yunhe.authority.domain.base.Theme;
import com.yunhe.authority.option.UserProperties;
import com.yunhe.authority.repository.authority.RoleRepository;
import com.yunhe.authority.repository.authority.UserRepository;
import com.yunhe.authority.repository.authority.impl.UserDao;
import com.yunhe.authority.service.authority.*;
import com.yunhe.authority.service.base.ThemeService;
import com.yunhe.authority.util.MyHeaderUtil;
import com.yunhe.common.constant.LogConsts;
import com.yunhe.common.constant.SystemConsts;
import com.yunhe.common.exception.*;
import com.yunhe.common.filter.ServerContextHolder;
import com.yunhe.common.model.PageParam;
import com.yunhe.common.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yunhe.common.util.CollectionUtil;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户Service
 * @author liuronglei
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private MenuService menuService;
    @Autowired
    private HomePageService homePageService;
    @Autowired
    private FirmService firmService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ThemeService themeService;
    @Autowired
    private UserProperties userProperties;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private LogUtil logUtil;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MyHeaderUtil myHeaderUtil;

    @Autowired
    private StationService stationService;

    @Autowired
    private OrganizationService orgService;

    private static final String menu = "用户管理";
    private static final String SALT_M = "yunhe";
    private static final String SALT_V = "@yqlh";

    /**
     * 用户对象处理和判断
     *
     * @param user 用户对象
     */
    private void processBeforeSave(User user)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        //判断账号、用户密码、姓名是否为空
        if (StringUtil.isEmpty(user.getPhone())
                || StringUtil.isEmpty(user.getPassword())
                || StringUtil.isEmpty(user.getTitle())) {
            throw new ArgumentErrorException("手机号、用户密码、姓名不能为空");
        }
        //判断所属单位、首页是否为空
//        if (user.getFirm() == null
//                || user.getFirm().getId() == null) {
//            throw new ArgumentErrorException("所属单位不能为空");
//        }
        //用户名统一为手机号
        user.setName(user.getPhone());
        //判断手机号是否已经被注册
        User userByPhone = this.findByPhone(user.getName());
        if (userByPhone != null) {
            if (user.getId() == null || userByPhone.getId().longValue() != user.getId().longValue()) {
                throw new UniqueConstraintsException("该手机号已有账户，直接登录或重新输入");
            }
        }

//        //先保留单位和首页引用，避免userByName将其覆盖
//        Firm firm = null;
//        if (user.getFirm() != null) {
//            firm = firmService.findByFirmId(user.getFirm().getId());
//        }
//        HomePage homePage = null;
//        if (user.getHomePage() != null && user.getHomePage().getId() != null && user.getHomePage().getId() > 0) {
//            homePage = homePageService.findByHomePageId(user.getHomePage().getId());
//        }
//        Theme theme = null;
//        if (user.getTheme() != null) {
//            theme = themeService.findByThemeId(user.getTheme().getId());
//        }
//        Role role = null;
//        if (user.getRole() != null && user.getRole().getId() != null) {
//            role = roleService.findByRoleId(user.getRole().getId());
//        } else {
//            throw new ArgumentErrorException("角色不能为空");
//        }
//
//        //绑定所属单位
//        if(firm != null) {
//            user.setFirm(firm);
//        } /*else {
//            throw new ObjectNotFoundException("找不到所属单位");
//        }*/
//        //绑定首页
//        if (user.getHomePage() != null && user.getHomePage().getId() != null) {
//            user.setHomePage(homePage);
//        }
//        if (role != null) {
//            user.setRole(role);
//        } else {
//            throw new ArgumentErrorException("角色不存在");
//        }
//        //绑定主题
//        user.setTheme(theme);
//        //密码加密
//        if (user.getId() == null) {
//            user.setPassword(MD5Util.encode(user.getPassword(), SALT_M));
//            //判断受否是角色管理员
//            List<User> list = (List<User>) roleService.findActiveUsersById(role.getId());
//            if (list == null || list.size() == 0) {
//                user.setAdmin(true);
//            }
//        }
//        //判断手机号是否被绑定
//        if (user.getPhone() != null) {
//            String phone = user.getPhone();
//            List<User> list = (List<User>) userRepository.findByPhone(phone);
//            if (list.size() > 0) {
//                if (user.getId() == null) {
//                    throw new UniqueConstraintsException("该手机号已被注册");
//                } else {
//                    User userByPhone = list.get(0);
//                    if (userByPhone.getId().longValue() != user.getId()) {
//                        throw new UniqueConstraintsException("该手机号已被注册");
//                    }
//                }
//            }
//        }
    }

    private User findByPhone(String phone) {
        return userRepository.findByPhone(phone);
    }

    /**
     * 新增用户
     *
     * @param user 新增对象
     * @param ascriptionOrgIds
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    @Override
    public User createUser(User user, Long stationId, Long firmId, String ascriptionOrgIds, String orgIds, String roleIds)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        user.setId(null);
        user.setCreateTime(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(), new Date()));
        processBeforeSave(user);
        if((stationId == null && firmId == null) || StringUtil.isEmpty(ascriptionOrgIds) || StringUtil.isEmpty(roleIds)){
            throw new ArgumentErrorException("请关联对应的项目、项目角色、项目组织架构！");
        }
        //密码加密
        if (user.getId() == null) {
            user.setPassword(MD5Util.encode(user.getPassword(), SALT_M));
        }
        if(stationId == null && firmId != null){
            user.setItemsNumber("1/0");
            Firm firm = firmService.findByFirmId(stationId);
            String system = firm.getSystem();
            if("1".equals(system)){
                user.setBackUser(true);
            }
        }else if(stationId != null && firmId == null){
            user.setItemsNumber("0/1");
            Station station = stationService.findById(stationId);
            String system = station.getSystem();
            if("1".equals(system)){
                user.setBackUser(true);
            }
        }
        User newUser = userRepository.save(user);
//        if (newUser != null) {
//            logUtil.createLog(LogConsts.LOG_TYPE_CODE.ACTION, menu, SystemConsts.ACTION.ADD);
//        }
        bindUser(newUser.getId(),firmId,stationId,ascriptionOrgIds,orgIds,roleIds);
        return newUser;
    }

    private void bindUser(Long id, Long firmId, Long stationId, String ascriptionOrgIds, String orgIds, String roleIds) throws ArgumentErrorException, ObjectNotFoundException {
        String[] split = roleIds.split(",");
        if(split == null || split.length ==0){
            throw new ArgumentErrorException("请关联对应的项目角色！");
        }
        List<Long> orgIdList = new ArrayList<>();
        if(!StringUtils.isEmpty(orgIds)){
            String[] orgIdArrays = orgIds.split(",");
            for (String s : orgIdArrays) {
                orgIdList.add(Long.valueOf(s));
            }
        }

        List<Long> belongOrgIdList = new ArrayList<>();
        if(!StringUtils.isEmpty(ascriptionOrgIds)){
            String[] orgIdArrays = ascriptionOrgIds.split(",");
            for (String s : orgIdArrays) {
                belongOrgIdList.add(Long.valueOf(s));
            }
        }

        List<Long> roleIdList = new ArrayList<>();
        for (String s : split) {
            roleIdList.add(Long.valueOf(s));
        }
        if(firmId != null && stationId == null ){
            //与单位进行绑定
            Firm firm = firmService.findByFirmId(firmId);
            if(firm != null){
                userRepository.bindFirms(id,firmId);
                //与单位组织进行相关绑定
                //与协同部门进行关系绑定
                if(!CollectionUtil.isEmpty(orgIdList)){
                    for (Long orgId : orgIdList) {
                        userRepository.unbindFirmUserAndOrg(id,firmId,orgId);
                        userRepository.bindFirmOrg(id,firmId,orgId);
                    }
                }
                //与归属部门绑定关系
                for (Long ascriptionOrgId : belongOrgIdList) {
                    userRepository.unbindFirmAscriptionOrg(id,firmId,ascriptionOrgId);
                    userRepository.bindFirmAscriptionOrg(id,firmId,ascriptionOrgId);
                }
                for (Long roleId : roleIdList) {
                    userRepository.unbindFirmRole(id,firmId,roleId);
                }
                //绑定相关单位角色
                userRepository.bindFirmRole(id,firmId,roleIdList);
            }else {
                throw new ObjectNotFoundException("找不到所属单位");
            }
        }else if(firmId == null && stationId != null){
            Station station = stationService.findById(stationId);
            if(station != null){
                //与项目进行绑定
                userRepository.bindStation(id,stationId);
                //与项目组织进行相关绑定
                //与协同部门进行关系绑定
                if(!CollectionUtil.isEmpty(orgIdList)){
                    for (Long orgId : orgIdList) {
                        userRepository.unbindStationUserAndOrg(id,stationId,orgId);
                        userRepository.bindStaionOrg(id,stationId,orgId);
                    }
                }
                //与归属部门绑定关系
                for (Long ascriptionOrgId : belongOrgIdList) {
                    userRepository.unbindStaionAscriptionOrg(id,stationId,ascriptionOrgId);
                    userRepository.bindStaionAscriptionOrg(id,stationId,ascriptionOrgId);
                }
                for (Long roleId : roleIdList) {
                    userRepository.unbindStationRole(id,stationId,roleId);
                }
                //绑定相关项目角色
                userRepository.bindStationRole(id,stationId,roleIdList);
            }else {
                throw new ObjectNotFoundException("找不到所属项目");
            }
        }
    }

    /**
     * 批量新增用户
     *
     * @param list 用户列表
     */
    @Override
    @Transactional
    public Iterable<User> createUser(List<User> list)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        for (User user : list) {
            user.setId(null);
            user.setCreateTime(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(), new Date()));
            processBeforeSave(user);
        }
        Iterable<User> newList = userRepository.saveAll(list);
//        if (newList != null) {
//            logUtil.createLog(LogConsts.LOG_TYPE_CODE.ACTION, menu, SystemConsts.ACTION.ADD);
//        }
        return newList;
    }

    /**
     * 根据id删除用户
     *
     * @param userIds 用户ID
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    @Override
    public void deleteUser(String userIds) throws UniqueConstraintsException, ArgumentErrorException {
        if(StringUtil.isEmpty(userIds)){
            throw new ArgumentErrorException("请选择要删除的账号信息");
        }
        String[] split = userIds.split(",");
        if(split.length<=0){
            throw new ArgumentErrorException("请选择要删除的账号信息");
        }
        List<Long> ids = new ArrayList<>();
        for (String s : split) {
            ids.add(Long.valueOf(s));
        }
        //解除用户与单位  项目  角色  组织之间的关系
        userRepository.unbindAllFirms(ids);
        userRepository.unbindAllStations(ids);
        userRepository.unbindAllOrgs(ids);
        userRepository.unbindAllSynergyOrgs(ids);
        userRepository.unbindAllRoles(ids);
        //删除用户
        userRepository.deleteByIds(ids);
        logUtil.createLog(LogConsts.LOG_TYPE_CODE.ACTION, menu, SystemConsts.ACTION.DELETE);
    }

    /**
     * 更新用户
     *
     * @param user 要更新的用户对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public User updateUser(User user)
            throws ArgumentErrorException, ObjectNotFoundException, UniqueConstraintsException {
        User olduser = this.findByUserId(user.getId());
        if (olduser== null) {
            throw new ObjectNotFoundException("找不到ID为" + user.getId() + "的用户");
        }
        Optional.ofNullable(user.getName()).ifPresent(olduser::setName);
        Optional.ofNullable(user.getTitle()).ifPresent(olduser::setTitle);
        Optional.ofNullable(user.getSex()).ifPresent(olduser::setSex);
        Optional.ofNullable(user.getActivity()).ifPresent(olduser::setActivity);
        Optional.ofNullable(user.getMail()).ifPresent(olduser::setMail);
        olduser.setPhotoUrl(user.getPhotoUrl());
        olduser.setItemsNumber(olduser.getItemsNumber());
        olduser.setUpdateTime(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(), new Date()));
        processBeforeSave(olduser);
        User newUser = userRepository.save(olduser);
//        if (newUser != null) {
//            logUtil.createLog(LogConsts.LOG_TYPE_CODE.ACTION, menu, SystemConsts.ACTION.EDIT);
//        }
        String userName = redisClient.get("UserName:" + user.getId());
        if(!StringUtil.isEmpty(userName)){
            redisClient.set("UserName:" + user.getId(), JSON.toJSONString(user));
        }
        return newUser;
    }

    /**
     * 更新用户
     * @param userId     用户ID
     * @param name       账号
     * @param title      昵称
     * @param phone      电话
     * @param firmId     单位ID
     * @param homePageId 首页ID
     * @param themeId    主题ID
     * @param activity   是否可用
     * @param admin
     */
    @Override
    @Transactional
    public User updateUser(Long userId, String name, String title, String phone, Long firmId, Long homePageId, Long themeId, Boolean activity, Boolean admin) throws ArgumentErrorException, ObjectNotFoundException, UniqueConstraintsException {
        User user = this.findByUserId(userId);
        if (user == null) {
            throw new ObjectNotFoundException("找不到ID为" + userId + "的用户");
        }
        Boolean adminValue = user.getAdmin();
        Optional.ofNullable(name).ifPresent(user::setName);
        Optional.ofNullable(title).ifPresent(user::setTitle);
        Optional.ofNullable(name).ifPresent(user::setName);
        //Optional.ofNullable(activity).ifPresent(user::setActivity);
        Optional.ofNullable(admin).ifPresent(user::setAdmin);
//        if (firmId != null) {
//            Firm firm = new Firm();
//            firm.setId(firmId);
//            user.setFirm(firm);
//        }
        if (homePageId != null) {
            HomePage homePage = new HomePage();
            homePage.setId(homePageId);
            //user.setHomePage(homePage);
        }
        if (themeId != null) {
            Theme theme = new Theme();
            theme.setId(themeId);
            //user.setTheme(theme);
        }
        if (StringUtils.isNotEmpty(phone)) {
            if (!"-1".equals(phone)) {
                user.setPhone(phone);
            } else {
                user.setPhone(null);
            }
        }
        processBeforeSave(user);
        if (admin != null) {
            if (admin.equals(false) && adminValue.equals(true)) {
                throw new UniqueConstraintsException("该用户已经是管理员！");
            }
            List<Role> list = (List)findRolesByUserId(userId);
            Role role = list.get(0);
            updateRoleAdmin(userId, role.getId());
        }
        User newUser = userRepository.save(user);
        if (newUser != null) {
            logUtil.createLog(LogConsts.LOG_TYPE_CODE.ACTION, menu, SystemConsts.ACTION.EDIT);
        }
        String userName = redisClient.get("UserName:" + user.getId());
        if(!StringUtil.isEmpty(userName)){
            redisClient.set("UserName:" + user.getId(), JSON.toJSONString(user));
        }
        return newUser;
    }

    /**
     * 根据ID获得用户对象
     *
     * @param userId 用户ID
     */
    @Override
    public User findByUserId(Long userId) {
        return userRepository.findById(userId).orElse(null);
    }

    /**
     * 根据账号获得用户对象
     *
     * @param name 账号
     */
    @Override
    public User findByName(String name) {
        return userRepository.findByName(name);
    }

    /**
     * 根据账号和密码获得用户对象
     *
     * @param name     账号
     * @param password 密码
     */
    @Override
    public User findByNameAndPassword(String name, String password) throws ArgumentErrorException {
        if (StringUtil.isEmpty(name) || StringUtil.isEmpty(password)) {
            throw new ArgumentErrorException("用户名、密码不能为空");
        }
        return userRepository.findByNameAndPassword(name.toLowerCase(), MD5Util.encode(password, SALT_M));
    }

    /**
     * 根据条件获得所有用户对象
     *  @param name      账号
     * @param title     昵称
     * @param pageParam 分页对象
     */
    @Override
    public Iterable<User> getUserByCondition(String name, String title, PageParam pageParam) {
        Iterable<User> results;
        List<String> defaultSortParam = new ArrayList<>();
        defaultSortParam.add("-createTime");
        if (QueryUtil.needPaging(pageParam)) {
            if (pageParam.getSort() == null) {
                pageParam.setSort(defaultSortParam);
            }
            Pageable pageable = QueryUtil.getPageRequest(pageParam);
            if (StringUtils.isEmpty(name) && StringUtils.isEmpty(title)) {
                results = userRepository.findAll(pageable);
            } else {
                results = userRepository.findByNameLikeOrTitleLike(name, title, pageable);
            }
        } else {
            Sort sort = pageParam == null ? null : QueryUtil.getSort(pageParam.getSort());
            if (sort == null) {
                sort = QueryUtil.getSort(defaultSortParam);
            }
            if (StringUtils.isEmpty(name) && StringUtils.isEmpty(title)) {
                results = userRepository.findAll(sort);
            } else {
                results = userRepository.findByNameLikeOrTitleLike(name, title, sort);
            }
        }
        return results;
    }

    /**
     * 根据条件获得所有用户对象
     *
     * @param userId
     * @param roleId
     * @param name      账号
     * @param title     昵称
     * @param phone
     * @param pageParam 分页对象
     */
    @Override
    public Iterable<User> getUserByCondition(Long userId,
                                             Long roleId,
                                             String name,
                                             String title,
                                             String phone,
                                             PageParam pageParam) {
        List<String> sortList = pageParam.getSort();
        if (sortList == null) {
            sortList = new ArrayList<>();
        }
        sortList.add("createTime");
        pageParam.setSort(sortList);
        if (userId != null || roleId != null || StringUtils.isNotEmpty(name) || StringUtils.isNotEmpty(title)
                || StringUtils.isNotEmpty(phone)) {
            List<Role> roles = (List<Role>) roleService.findRolesByUserId(userId != null ? userId : 0L);
            List<User> users;
            if (StringUtils.isNotEmpty(title) || StringUtils.isNotEmpty(name) || StringUtils.isNotEmpty(phone)) {
                users = (List<User>) userRepository.findByNameLikeOrTitleLikeOrPhoneLike(name, title, phone);
            } else {
                users = (List<User>) userRepository.findAll();
            }
            List<User> users2;
            if (roleId != null) {
                users2 = (List<User>) userRepository.findUsersByRoleId(roleId);
            } else if (userId != null) {
                users2 = (List<User>) userRepository.findAllById(userId);
            } else {
                users2 = (List<User>) userRepository.findAll();
            }
            List<User> list = new ArrayList<>();
            if (users2 != null && users2.size() > 0) {
                for (User user : users) {
                    for (User u : users2) {
                        if (user.getId().longValue() == u.getId()) {
                            list.add(user);
                        }
                    }
                }
            }
            if (roles != null && roles.size() > 0) {
                Role role = roles.get(0);
                if (role.getLevel() == 0) {
                    if (QueryUtil.needPaging(pageParam)) {
                        Pageable pageable = QueryUtil.getPageRequest(pageParam);
                        List<User> pages = new ArrayList<>();
                        long page = pageable.getOffset();
                        int size = pageable.getPageSize();
                        for (int i = 0; i < list.size(); i++) {
                            if (i >= page && i < page + size) {
                                pages.add(list.get(i));
                            }
                        }
                        return new PageImpl<>(pages, pageable, list.size());
                    } else {
                        return list;
                    }
                } else {
                    List<User> temp = new ArrayList<>();
                    for (User user : list) {
//                        if (user.getActivity().equals(false) || user.getRole().getActivity().equals(false)) {
//                            temp.add(user);
//                        }
                    }
                    list.removeAll(temp);
                    if (QueryUtil.needPaging(pageParam)) {
                        Pageable pageable = QueryUtil.getPageRequest(pageParam);
                        List<User> pages = new ArrayList<>();
                        long page = pageable.getOffset();
                        int size = pageable.getPageSize();
                        for (int i = 0; i < list.size(); i++) {
                            if (i >= page && i < page + size) {
                                pages.add(list.get(i));
                            }
                        }
                        return new PageImpl<>(pages, pageable, list.size());
                    } else {
                        return list;
                    }
                }
            } else {
                return getUserByCondition(name, title, pageParam);
            }
        } else {
            return userRepository.findAll();
        }
    }

    /**
     * 绑定角色
     *
     * @param userId 用户ID
     * @param roleId 角色ID
     */
    @Override
    @Transactional
    public void bindRole(Long userId, Long roleId)
            throws DatabaseProcessException {
        List<User> users = (List) roleService.findUsersById(roleId);
        User user = findByUserId(userId);
        if (users == null || users.size() == 0) {
            user.setAdmin(true);
        }
        userRepository.bindRole(userId, roleId);
    }

    @Override
    @Transactional
    public void updateRoleAdmin(Long id, Long roleId)
            throws UniqueConstraintsException {
        List<User> list = (List<User>)roleService.findUsersById(roleId);
        if (list != null && list.size() > 1) {
            userRepository.updateRoleAdmin(id, roleId);
        } else {
            throw new UniqueConstraintsException("只有一个用户不能转让管理员");
        }
    }

    /**
     * 解绑角色
     *
     * @param userId 用户ID
     * @param roleId 角色ID
     */
    @Override
    @Transactional
    public void unbindRole(Long userId, Long roleId) {
        userRepository.unbindRole(userId, roleId);
    }

    /**
     * 批量更新角色绑定
     *
     * @param userId     用户ID
     * @param roleIdList 角色ID列表
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateRole(Long userId, List<Long> roleIdList)
            throws ArgumentErrorException {
        if (roleIdList != null && roleIdList.size() > 0) {
            User user = findByUserId(userId);
            List<Role> roles = (List<Role>) findRolesByUserId(userId);
            Role role = roles.get(0);
            Long rId = roleIdList.get(0);
            if (user.getAdmin() && !role.getId().equals(rId)) {
                throw new ArgumentErrorException("该用户是角色管理员，请先转移角色管理员");
            }
            //先解绑
            //userRepository.unbindAllRoles(userId);
            //再绑定
            for (Long roleId : roleIdList) {
                userRepository.bindRole(userId, roleId);
            }
        }
    }

    /**
     * 更新首页绑定
     *
     * @param userId     用户ID
     * @param homePageId 首页对象ID
     */
    @Override
    @Transactional
    public void updateHomePage(Long userId, Long homePageId)
            throws ObjectNotFoundException {
        User user = this.findByUserId(userId);
        if (user == null) {
            throw new ObjectNotFoundException("找不到要修改的用户");
        }
        HomePage homePage = homePageService.findByHomePageId(homePageId);
        if (homePage == null) {
            throw new ObjectNotFoundException("找不到要绑定的首页");
        }
        //user.setHomePage(homePage);
        userRepository.save(user);
    }

    /**
     * 更新主题绑定
     *
     * @param userId  用户ID
     * @param themeId 主题对象ID
     */
    @Override
    @Transactional
    public void updateTheme(Long userId, Long themeId)
            throws ObjectNotFoundException {
        User user = this.findByUserId(userId);
        if (user == null) {
            throw new ObjectNotFoundException("找不到要修改的用户");
        }
        Theme theme = themeService.findByThemeId(themeId);
        if (theme == null) {
            throw new ObjectNotFoundException("找不到要绑定的主题");
        }
        //user.setTheme(theme);
        userRepository.save(user);
    }

    /**
     * 获得用户绑定的角色列表
     *
     * @param userId 用户ID
     */
    @Override
    public Iterable<Role> findRolesByUserId(Long userId) {
        return roleRepository.findRolesByUserId(userId);
    }

    /**
     * 获得用户有权限的菜单列表
     *
     * @param userId 用户ID
     */
    @Override
    public Iterable<Menu> findMenusByUserId(Long userId) {
        User user = findByUserId(userId);
//        if (user != null && user.getFirm() != null) {
//            return menuService.findMenusByUserId(user.getFirm().getCode(), userId);
//        } else {
//            return null;
//        }
        return null;
    }

    /**
     * 获得用户有权限的菜单列表
     *
     * @param userId 用户ID
     */
//    @Override
//    public Iterable<Menu> findAppMenusByUserId(Long userId) {
//        Firm firm = userRepository.findFirmByUserId(userId);
//        return menuService.findAppMenusByUserId(firm.getCode(), userId);
//    }

    /**
     * 获得用户绑定的首先
     *
     * @param userId 用户ID
     */
    @Override
    public HomePage findHomePageByUserId(Long userId) {
        return homePageService.findHomePageByUserId(userId);
    }

    /**
     * 根据服务名获得用户联系方式
     *
     * @param serviceName 服务名称
     */
    @Override
    public Iterable<String> findUserPhoneByServiceName(String serviceName) {
        return userRepository.findUserPhoneByServiceName(serviceName);
    }

    /**
     * 根据用户ID获得主题
     *
     * @param id 用户ID
     */
    @Override
    public Theme findThemeByUserId(Long id) {
        return userRepository.findThemeByUserId(id);
    }

    /**
     * 修改密码
     *
     * @param id       用户ID
     * @param password 用户密码
     */
    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public User updatePassword(Long id, String phone, String password, String newPassword)
            throws UsernamePasswordException {
        User user = userRepository.findByPhoneAndPassword(phone, MD5Util.encode(password, SALT_M));
        if (user != null && user.getId().longValue() == id) {
            User newUser = userRepository.updatePassword(id, MD5Util.encode(newPassword, SALT_M));
            if (newUser != null) {
                logUtil.createLog(LogConsts.LOG_TYPE_CODE.ACTION, "修改密码", SystemConsts.ACTION.EDIT);
            }
            //重置密码第一次修改密码之后 清除重置密码标记
            redisClient.del(id + "-resetPassword");
            return newUser;
        } else {
            throw new UsernamePasswordException("旧密码输入错误");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public List<User> resetPassword(String ids)
            throws UsernamePasswordException, ArgumentErrorException {
        if(StringUtil.isEmpty(ids)){
            throw new ArgumentErrorException("请选择用户进行操作！");
        }
        String[] split = ids.split(",");
        List<User> result = new ArrayList<>();
        for (String id : split) {
            List<Role> roles = (List) roleService.findRolesByUserId(Long.valueOf(id));
            if (roles != null && roles.size() > 0) {
                Role role = roles.get(0);
                if (role.getLevel() == 0) {
                    User user = userRepository.updatePassword(Long.valueOf(id), MD5Util.encode(MD5Util.encode(userProperties.getRootDefaultPassword(), SALT_V), SALT_M));
                    //发短信
                    if (user != null && user.getPhone() != null) {
                        String phone = user.getPhone();
                        String password = userProperties.getRootDefaultPassword();
                        Map<String, String> map = new HashMap<>();
                        map.put("code", password);
                        String templateCode = "SMS_218727647";
                        String templateParam = "{\"code\":\"" + password + "\"}";
                        try {
                            SmsUtil.sendSms(phone, map, templateCode, templateParam);
                        } catch (Exception e) {
                            throw new ArgumentErrorException("短信发送失败！");
                        }
                        result.add(user);
                        //用户校验重置密码后用户第一次登录提示修改密码
                        redisClient.set(user.getId()+"-resetPassword","success");
                    }
                } else {
                    User user = userRepository.updatePassword(Long.valueOf(id), MD5Util.encode(MD5Util.encode(userProperties.getDefaultPassword(), SALT_V), SALT_M));
                    //发短信
                    if (user != null && user.getPhone() != null) {
                        String phone = user.getPhone();
                        String password = userProperties.getDefaultPassword();
                        Map<String, String> map = new HashMap<>();
                        map.put("code", password);
                        String templateCode = "SMS_218727647";
                        String templateParam = "{\"code\":\"" + password + "\"}";
                        try {
                            SmsUtil.sendSms(phone, map, templateCode, templateParam);
                        } catch (Exception e) {
                            throw new ArgumentErrorException("短信发送失败！");
                        }
                        result.add(user);
                        redisClient.set(user.getId()+"-resetPassword","success");
                    }
                }
            }
        }
        return result;
    }

    @Override
    public String getPasswordByUsername(String name) {
        return null;
    }

    @Override
    public Iterable<User> findUsersByRoleId(Long roleId, Long userId) {
        Role role;
        if (userId != null) {
            List<Role> list = (List) findRolesByUserId(userId);
            role = list.get(0);
        } else {
            role = roleService.findByRoleId(roleId);
        }
        if (role != null) {
            if (role.getLevel() == 0) {
                return userRepository.findUsersByRoot(role.getId());
            } else {
                return userRepository.findUsers(role.getId());
            }
        } else {
            return null;
        }
    }

    /**
     * 根据单位id查询用户列表
     * @param firmId 单位ID
     * @param queryData 查询条件
     * @param pageParam 分页对象
     * @return
     */
    @Override
    public Page<User> findUsersByFirmId(Long firmId, String queryData, PageParam pageParam) {
        Pageable pageable = QueryUtil.getPageRequest(pageParam);
        return userRepository.findByFirmId(firmId, queryData, pageable);
    }

    /**
     * 获得所有企业的用户列表
     * @param queryData 查询条件
     * @param pageParam 分页对象
     * @return
     */
    @Override
    public Page<User> getAllCompanyUser(String queryData, PageParam pageParam) {
        Pageable pageable = QueryUtil.getPageRequest(pageParam);
        return userRepository.findAllCompanyUser(queryData, pageable);
    }

    @Override
    public void sendValidateMsg(String phone, String type) throws ArgumentErrorException {
        Random random = new Random();
        try {
            //校验手机号是否存在
            User user = this.findByPhone(phone);
            if(user == null){
                throw new ArgumentErrorException("手机号不存在！");
            }
            String currentTimeStr = redisClient.get(phone + ":" + type + ":currentTime");
            if(!StringUtil.isEmpty(currentTimeStr)){
                Long currentTime = Long.parseLong(currentTimeStr);
                if((System.currentTimeMillis()-currentTime) <= 60*1000){
                    throw new ArgumentErrorException("该手机号已经1分钟之内发送过验证码！");
                }
            }
            String templateCode = "SMS_212560079";
            if("login".equals(type)){
                templateCode = "SMS_212560079";
            }else if("changePassword".equals(type)){
                templateCode = "SMS_212560076";
            }
            if(StringUtil.isEmpty(templateCode)){
                throw new ArgumentErrorException("暂无对应的短信模板！");
            }
            //第四次给出提示 获取验证码过于频繁，请5分钟后再试！
            String count = redisClient.get(phone + "-" + type + "count");
            if(!StringUtil.isEmpty(count) && Integer.valueOf(count)==4){
                throw new ArgumentErrorException("获取验证码过于频繁，请5分钟后再试！");
            }
            if(!StringUtil.isEmpty(count) && Integer.valueOf(count)==2){
                redisClient.set(phone + "-" + type + "count",String.valueOf(Integer.valueOf(count)+1),6*60);
            }else if(StringUtil.isEmpty(count) || "1".equals(count)){
                count = StringUtil.isEmpty(count)?"0":count;
                redisClient.set(phone + "-" + type + "count",String.valueOf(Integer.valueOf(count)+1),6*60);
            }else if(!StringUtil.isEmpty(count) && Integer.valueOf(count)==3){
                redisClient.set(phone + "-" + type + "count",String.valueOf(Integer.valueOf(count)+1),6*60);
            }
            Map<String, String> map = new HashMap<>();
            int code = random.nextInt(900000) + 100000;
            String validateCode = code + "";
            map.put("code", validateCode);
            String templateParam = "{\"code\":\"" + validateCode + "\"}";
            SmsUtil.sendSms(phone, map, templateCode, templateParam);
            redisClient.set(phone+"-"+type, validateCode, 30*60);
            redisClient.set(phone + ":" + type + ":currentTime", String.valueOf(System.currentTimeMillis()),30*60);
        } catch (Exception e) {
            if(StringUtil.isEmpty(e.getMessage())){
                throw new ArgumentErrorException("获取验证码失败， 请重新获取！");
            }else {
                throw new ArgumentErrorException(e.getMessage());
            }

        }
    }

    @Override
    public String getValidateCode(String phone) throws ArgumentErrorException {
        String code = redisClient.get(phone);
        if (StringUtil.isEmpty(code)) {
            throw new ArgumentErrorException("验证码失效");
        } else {
            return code;
        }
    }

    @Override
    public User verification(String name, String password) throws ArgumentErrorException {
        User user = userRepository.findByNameAndPassword(name, MD5Util.encode(password, SALT_M));
        if (user == null) {
            throw new ArgumentErrorException("密码输入错误");
        }
        return user;
    }

    @Override
    public void verification(Long userId, String key, Boolean agree) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> valueMap = new HashMap<>();
        valueMap.put("count", 0);
        valueMap.put("firstAgree", false);
        valueMap.put("firstUserId", null);
        valueMap.put("firstUserTitle", null);
        valueMap.put("firstUserName", null);
        valueMap.put("secondAgree", false);
        valueMap.put("secondUserId", null);
        valueMap.put("secondUserTitle", null);
        valueMap.put("secondUserName", null);
        String value = redisClient.get("QRCode" + key);
        //如果是第二个人 先取出操作发起人
        if (value != null) {
            //先验证用户权限
            valueMap = mapper.readValue(value, Map.class);
            Object object = valueMap.get("count");
            if (object != null && ((Number) object).intValue() < 2) {
                int count = ((Number) object).intValue();
                valueMap.put("count", count + 1);
                valueMap.put("secondAgree", agree);
                valueMap.put("secondUserId", userId);
                User user = findByUserId(userId);
                if (user != null && user.getTitle() != null) {
                    valueMap.put("secondUserTitle", user.getTitle());
                    valueMap.put("secondUserName", user.getName());
                }
            }
        } else {
            valueMap.put("count", 1);
            valueMap.put("firstAgree", agree);
            valueMap.put("firstUserId", userId);
            User user = findByUserId(userId);
            if (user != null && user.getTitle() != null) {
                valueMap.put("firstUserTitle", user.getTitle());
                valueMap.put("firstUserName", user.getName());
            }
        }
        String valueAsString = mapper.writeValueAsString(valueMap);
        redisClient.set("QRCode" + key, valueAsString, 86400);
    }

    @Override
    public Map<String, Object> getVerificationResult(String key) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        String valueString = redisClient.get("QRCode" + key);
        if (!StringUtil.isEmpty(valueString)) {
            Map<String, Object> valueMap = mapper.readValue(valueString, Map.class);
            return valueMap;
        } else {
            return new HashMap<>();
        }
    }

    @Override
    public List<User> findUsersByMenu(String menuName) {
        return userRepository.findUsersByMenu(menuName);
    }

    /**
     * 根据姓名获得用户列表
     * @param title 姓名
     */
    @Override
    public Iterable<User> findByTitleContaining(String title) {
        return userRepository.findByTitleContaining(title);
    }

    /**
     * 根据账号列表获得用户列表
     * @param nameList 账号列表
     */
    @Override
    public Iterable<User> findUsersByNames(List<String> nameList) {
        return userRepository.findUsersByNames(nameList);
    }

    @Override
    public Iterable<User> findByMenuName(String menuName) {
        return userRepository.findByMenuName(menuName);
    }

    /*
    public void unbindAllRoles(Long userId)
            throws DatabaseProcessException {
        List<Role> roles = findRolesByUserId(userId);
        for (Role role : roles) {
            Long roleId = role.getId();
            bindRole(userId, roleId);
        }
    }

    public void unbindRoles(Long userId, List<Long> roleIdList)
            throws DatabaseProcessException {
        for (Long roleId : roleIdList) {
            bindRole(userId, roleId);
        }
    }
    */

    /**
     * 根据手机号和密码登录
     * @param phone
     * @param password
     * @return
     * @throws ArgumentErrorException
     * @throws UsernamePasswordException
     */
    @Override
    public User findByPhoneAndPassword(String phone, String password) throws ArgumentErrorException, UsernamePasswordException {
        User user = userRepository.findByPhoneAndPassword(phone, MD5Util.encode(password, SALT_M));
        checkUser(user);
        return user;
    }

    @Override
    public User getUserByPhone(String phone) throws ObjectNotFoundException {
        User user = userRepository.findByPhone(phone);
        if(user == null){
            User newUser = new User();
            newUser.setName(phone);
            newUser.setPassword(MD5Util.encode(MD5Util.encode(userProperties.getDefaultPassword(), SALT_V), SALT_M));
            newUser.setActivity("1");
            newUser.setBackUser(false);
            User headerUser = myHeaderUtil.getHeaderUser();
            BackUser headerBackUser = myHeaderUtil.getHeaderBackUser();
            if(headerUser != null){
                newUser.setCreator(headerUser.getTitle());
            }else if(headerBackUser != null){
                newUser.setCreator(headerBackUser.getTitle());
            }

            newUser.setCreateTime(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(), new Date()));
            newUser.setPhone(phone);
            return  userRepository.save(newUser);
        }
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void saveLoginRecord(User user) {
        user.setActivityTitle(null);
        user.setLastLoginSystemTitle(null);
        user.setSexTitle(null);
        userRepository.save(user);
    }

    /**
     * 校验验证码是否正确以及修改密码
     * @param phone
     * @param verificationCode
     * @param password
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public User changePassword(String phone, String verificationCode, String password) throws ArgumentErrorException {
        if("000000".equals(verificationCode)){
            User user = userRepository.findByPhone(phone);
            if(user != null){
                User newUser = userRepository.updatePassword(user.getId(), MD5Util.encode(password, SALT_M));
                if (newUser != null) {
                    logUtil.createLog(LogConsts.LOG_TYPE_CODE.ACTION, "修改密码", SystemConsts.ACTION.EDIT);
                }
                redisClient.del(phone+"-"+"changePassword");
                return newUser;
            }else {
                throw new ArgumentErrorException("该手机号未注册用户，请重新输入手机号！");
            }
        }else {
            String reult = redisClient.get(phone+"-"+"changePassword");
            if(StringUtil.isEmpty(reult)){
                throw new  ArgumentErrorException("验证码已失效");
            }
            if(verificationCode.equals(reult)){
                User user = userRepository.findByPhone(phone);
                if(user != null){
                    User newUser = userRepository.updatePassword(user.getId(), MD5Util.encode(password, SALT_M));
                    if (newUser != null) {
                        logUtil.createLog(LogConsts.LOG_TYPE_CODE.ACTION, "修改密码", SystemConsts.ACTION.EDIT);
                    }
                    redisClient.del(phone+"-"+"changePassword");
                    return newUser;
                }else {
                    throw new ArgumentErrorException("该手机号未注册用户，请重新输入手机号！");
                }
            }else {
                throw new  ArgumentErrorException("验证码不正确，请重新输入");
            }
        }
    }

    @Override
    public User findByPhoneAndVerificationCode(String phone, String verificationCode) throws ArgumentErrorException, UsernamePasswordException {

        if(!verificationCode.equals("000000")){
            String reult = redisClient.get(phone+"-"+"login");
            if(StringUtil.isEmpty(reult)){
                throw new  ArgumentErrorException("验证码已失效");
            }
            if(!verificationCode.equals(reult)){
                throw new ArgumentErrorException("验证码输入错误");
            }
        }
        User user = userRepository.findByPhone(phone);
        checkUserByPhone(user);
        return user;
    }

    private void checkUserByPhone(User user) throws ArgumentErrorException, UsernamePasswordException {
        if (user == null) {
            throw new ArgumentErrorException("对应手机号未注册，请重新输入手机号！");
        }
        if (!user.getActivity().equals("1")) {
            throw new UsernamePasswordException("该用户已过期，无法登录");
        }
        if (!CollectionUtil.isEmpty(user.getRole())) {
            List<Role> roles = user.getRole();
            List<Role> collect = roles.stream().filter(role -> {
                return !role.getActivity().equals("1");
            }).collect(Collectors.toList());
            if(!CollectionUtil.isEmpty(collect)){
                throw new UsernamePasswordException("该用户已过期，无法登录");
            }else {
                List<String> roleTitles = roles.stream().filter(role -> {
                    return role.getActivity().equals("1");
                }).map(role -> role.getName()).collect(Collectors.toList());
                if(!roleTitles.contains("superRoot")){
                    List<Long> roleIds = roles.stream().filter(role -> {
                        return role.getActivity().equals("1");
                    }).map(role -> role.getId()).collect(Collectors.toList());
                    List<Station> list = (List<Station>)stationService.findByRoleIds(roleIds);
                    List<Firm> firms = (List<Firm>) firmService.findByRoleIds(roleIds);
                    if (CollectionUtil.isEmpty(list) && CollectionUtil.isEmpty(firms)) {
                        throw new UsernamePasswordException("当前用户没有数据权限，请联系管理员");
                    }
                }
            }
        } else if (CollectionUtil.isEmpty(user.getRole())) {
            throw new UsernamePasswordException("该用户已过期，无法登录");
        }
    }

    private void checkUser(User user) throws ArgumentErrorException, UsernamePasswordException {
        if (user == null) {
            throw new ArgumentErrorException("手机号、密码错误");
        }
        if (!user.getActivity().equals("1")) {
            throw new UsernamePasswordException("该用户已过期，无法登录");
        }
        if (!CollectionUtil.isEmpty(user.getRole())) {
            List<Role> roles = user.getRole();
            List<Role> collect = roles.stream().filter(role -> {
                return !role.getActivity().equals("1");
            }).collect(Collectors.toList());
            if(!CollectionUtil.isEmpty(collect)){
                throw new UsernamePasswordException("该用户已过期，无法登录");
            }else {
                List<String> roleTitles = roles.stream().filter(role -> {
                    return role.getActivity().equals("1");
                }).map(role -> role.getName()).collect(Collectors.toList());
                if(!roleTitles.contains("superRoot")){
                    List<Long> roleIds = roles.stream().filter(role -> {
                        return role.getActivity().equals("1");
                    }).map(role -> role.getId()).collect(Collectors.toList());
                    List<Station> list = (List<Station>)stationService.findByRoleIds(roleIds);
                    List<Firm> firms = (List<Firm>) firmService.findByRoleIds(roleIds);
                    if (CollectionUtil.isEmpty(list) && CollectionUtil.isEmpty(firms)) {
                        throw new UsernamePasswordException("当前用户没有数据权限，请联系管理员");
                    }
                }
            }
        } else if (CollectionUtil.isEmpty(user.getRole())) {
            throw new UsernamePasswordException("该用户已过期，无法登录");
        }
    }

    @Override
    public Iterable<User> getUserByCondition(String phone, String title, String mail,
                                             String activity, String createStartTime,
                                             String createEndTime, String creator,
                                             String lastLoginStartTime, String lastLoginEndTime,
                                             String lastLoginSystem, PageParam pageParam) {
        Iterable<User> results = null;
        boolean admin  = true;
        List<String> defaultSortParam = new ArrayList<>();
        defaultSortParam.add("-createTime");
        if (QueryUtil.needPaging(pageParam)) {
            if (pageParam.getSort() == null) {
                pageParam.setSort(defaultSortParam);
            }
            Pageable pageable = PageRequest.of(pageParam.getPage()-1, pageParam.getSize());
            if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(title)
                    &&StringUtils.isEmpty(activity) && StringUtils.isEmpty(createStartTime)
                    &&StringUtils.isEmpty(createEndTime) && StringUtils.isEmpty(creator)
                    &&StringUtils.isEmpty(lastLoginStartTime) && StringUtils.isEmpty(lastLoginEndTime)
                    &&StringUtils.isEmpty(lastLoginSystem) && !admin) {
                results = userRepository.findAll(pageable);
            } else {
                results = userDao.findUsers(phone, title,mail,activity,createStartTime,
                        createEndTime,creator,lastLoginStartTime,lastLoginEndTime,lastLoginSystem, pageParam);
            }
        }
        return results;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void disableRecoveryUser(String ids, String activity, User headerUser, BackUser headerBackUser) throws ArgumentErrorException {
        if(StringUtil.isEmpty(ids)){
            throw new ArgumentErrorException("请选择用户进行操作！");
        }
        String[] split = ids.split(",");
        if(split.length<=0){
            throw new ArgumentErrorException("请选择用户进行操作！");
        }
        List<Long> userIds = new ArrayList<>();
        for (String s : split) {
            userIds.add(Long.valueOf(s));
        }
        String remark = null;
        if(headerUser != null){
            if("1".equals(activity)){
                remark = headerUser.getTitle()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"恢复";
            }else {
                remark = headerUser.getTitle()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"禁用";
            }
        }else if(headerBackUser != null){
            if("1".equals(activity)){
                remark = headerBackUser.getTitle()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"恢复";
            }else {
                remark = headerBackUser.getTitle()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"禁用";
            }
        }

        userRepository.updateActivity(userIds,activity,remark,DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date()));
    }

    @Override
    public Boolean resetFirstLogin(Long id) {
        String message = redisClient.get(id + "-resetPassword");
        if(StringUtil.isEmpty(message)){
            return false;
        }else {
            return true;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void bindProejctRoleOrg(Long id, Long firmId, Long stationId, String ascriptionOrgIds, String orgIds, String roleIds) throws ArgumentErrorException, ObjectNotFoundException {
        if(id == null){
            throw new ArgumentErrorException("请选择用户进行操作！");
        }
        User user = this.findByUserId(id);
        if(user == null){
         throw new  ObjectNotFoundException("该用户不存在！");
        }
        if((stationId == null && firmId == null) || ascriptionOrgIds ==null || StringUtil.isEmpty(roleIds)){
            throw new ArgumentErrorException("请关联对应的项目、项目角色、项目组织架构！");
        }
        String itemsNumber = user.getItemsNumber();


        if(stationId == null && firmId != null){
            //判断是否关联该项目
            User firmUser = userRepository.findByUserIdAndFirmId(id,firmId);
            if(firmUser != null){
                userRepository.unbindUserAndFirm(id, firmId);
                userRepository.unbindFirmUserAndRole(id,firmId);
                userRepository.unbindFirmUserAndOrg(id,firmId);
                userRepository.unbindFirmUserAndSynergyOrg(id,firmId);
                //throw new ArgumentErrorException("该项目已经绑定该用户！");
            }else {
                if(!StringUtil.isEmpty(itemsNumber)){
                    String[] split = itemsNumber.split("/");
                    user.setItemsNumber(Long.valueOf(split[0])+1+"/"+split[1]);
                }else {
                    user.setItemsNumber("1/0");
                }
            }


        }else if(stationId != null && firmId == null){
            User stationUser = userRepository.findByUserIdAndSationId(id,stationId);
            if(stationUser != null){
                userRepository.unbindUserAndStation(id, stationId);
                userRepository.unbindStationUserAndRole(id,stationId);
                userRepository.unbindStationUserAndOrg(id,stationId);
                userRepository.unbindStationUserAndSynergyOrg(id,stationId);
                //throw new ArgumentErrorException("该项目已经绑定该用户！");
            }else {
                if(!StringUtil.isEmpty(itemsNumber)){
                    String[] split = itemsNumber.split("/");
                    user.setItemsNumber(split[0]+"/"+(Long.valueOf(split[1])+1));
                }else {
                    user.setItemsNumber("0/1");
                }
            }


        }
        user.setUpdateTime(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date()));
        userRepository.save(user);
        bindUser(id,firmId,stationId, ascriptionOrgIds,orgIds,roleIds);
    }

    @Override
    public Iterable<ProjectUser> getUser(Long id, String type, String keywords, PageParam pageParam) throws ArgumentErrorException {
        Iterable<ProjectUser> users = null;
        if(id == null){
            throw new ArgumentErrorException("请选择用户进行操作！");
        }
        if(QueryUtil.needPaging(pageParam)){
            if("station".equals(type)){
                users = userDao.getStationUser(id, keywords,pageParam);
            }else if("firm".equals(type)){
                users = userDao.getFirmUser(id, keywords,pageParam);
            }
        }
        if(users != null){
            //匹配用户对应项目的组织角色
            for (ProjectUser user : users) {
                //查询角色
                List<Role> roles = (List<Role>) roleService.findByUserId(user.getUserId(),user.getStationId(),user.getFirmId());
                Map<String, String> roleMap = encapsulationRoleInfo(roles);
                user.setRoleIds(roleMap.get("ids"));
                user.setRoleTitle(roleMap.get("title"));
                //查询协同组织
                List<Organization> orgs = (List<Organization>) orgService.findByUserId(user.getUserId(),user.getStationId(),user.getFirmId());
                Map<String, String> map = encapsulationOrgInfo(orgs);
                user.setOrgIds(map.get("orgIds"));
                user.setOrgTitle(map.get("orgTitle"));
                //查询归属组织
                List<Organization> organizations = (List<Organization>) orgService.findBelongOrgByUserId(user.getUserId(),user.getStationId(),user.getFirmId());
                Map<String, String> belongMap = encapsulationOrgInfo(organizations);
                user.setAscriptionOrgId(belongMap.get("orgIds"));
                user.setAscriptionOrgTitle(belongMap.get("orgTitle"));
            }
        }
        return users;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void unbindUser(Long id, Long stationId, Long firmId) throws ObjectNotFoundException, ArgumentErrorException, UniqueConstraintsException {
        User user = this.findByUserId(id);
        if(user == null){
            throw new ObjectNotFoundException("该用户不存在！");
        }
        String itemsNumber = user.getItemsNumber();
        String[] split = itemsNumber.split("/");
        if(stationId == null && firmId != null){
            userRepository.unbindUserAndFirm(id,firmId);
            userRepository.unbindFirmUserAndRole(id,firmId);
            userRepository.unbindFirmUserAndOrg(id,firmId);
            userRepository.unbindFirmUserAndSynergyOrg(id,firmId);
            user.setItemsNumber(Long.valueOf(split[0])-1+"/"+split[1]);
        }else if(stationId != null && firmId == null){
            userRepository.unbindUserAndStation(id,stationId);
            userRepository.unbindStationUserAndRole(id,stationId);
            userRepository.unbindStationUserAndOrg(id,stationId);
            userRepository.unbindStationUserAndSynergyOrg(id,stationId);
            user.setItemsNumber(split[0]+"/"+(Long.valueOf(split[1])-1));
        }
        updateUser(user);
    }

    @Override
    public List<User> getUserByRoleType(String roleType) {

        return (List<User>) userRepository.findByRoleType(roleType);
    }

    @Override
    public Iterable<EmployeeUser> getUserByCondition(Long firmId, Long stationId, String roleTitle, PageParam pageParam) throws ArgumentErrorException {

        Iterable<EmployeeUser> users = null;
        if(firmId == null && stationId == null){
            throw new ArgumentErrorException("请选择项目进行相关用户查询！");
        }
        if(QueryUtil.needPaging(pageParam)){
            if(firmId != null && stationId == null){
                users = userDao.getFirmUserByCondition(firmId,roleTitle,pageParam);
            }else if(firmId == null && stationId != null){
                users = userDao.getStationUserByCondition(stationId,roleTitle,pageParam);
            }
            if(users != null){
                for (EmployeeUser user : users) {
                    //通过用户以及项目找组织和角色
                    findRoleAndOrg(roleTitle,user);
                }
            }
        }
        return users;
    }

    /**
     * 获取用户对应项目/单位的角色和单位
     * @param roleTitle
     * @param user
     */
    private void findRoleAndOrg(String roleTitle,EmployeeUser user) {
        List<Role> roles = new ArrayList<>();
        if(StringUtil.isEmpty(roleTitle)){
            roles = (List<Role>) roleService.findByUserId(user.getUserId(),user.getStationId(),user.getFirmId());
        }else {
            roles = (List<Role>) roleService.findByUserId(user.getUserId(),user.getStationId(),user.getFirmId(),roleTitle);
        }
        Map<String, String> roleMap = encapsulationRoleInfo(roles);
        user.setRoleIds(roleMap.get("ids"));
        user.setRoleTitle(roleMap.get("title"));
        //查询协同组织组织
        List<Organization> orgs = (List<Organization>) orgService.findByUserId(user.getUserId(),user.getStationId(),user.getFirmId());
        Map<String, String> map = encapsulationOrgInfo(orgs);
        user.setOrgIds(map.get("orgIds"));
        user.setOrgTitle(map.get("orgTitle"));
        //查询归属组织
        List<Organization> organizations = (List<Organization>) orgService.findBelongOrgByUserId(user.getUserId(),user.getStationId(),user.getFirmId());
        Map<String, String> belongMap = encapsulationOrgInfo(organizations);
        user.setAscriptionOrgId(belongMap.get("orgIds"));
        user.setAscriptionOrgTitle(belongMap.get("orgTitle"));

    }

    private Map<String,String> encapsulationRoleInfo(List<Role> roles){
        Map<String,String> map = new HashMap<>();
        if(!CollectionUtil.isEmpty(roles)){
            String roleIds = null;
            String roleTitle = null;
            for (Role role : roles) {
                if(StringUtil.isEmpty(roleIds)){
                    roleIds = role.getId().toString();
                }else {
                    roleIds = roleIds + ","+ role.getId();
                }
                if(StringUtil.isEmpty(roleTitle)){
                    roleTitle = role.getTitle();
                }else {
                    roleTitle = roleTitle + ","+role.getTitle();
                }
            }
            map.put("ids",roleIds);
            map.put("title",roleTitle);
        }
        return map;
    }

    private Map<String,String> encapsulationOrgInfo(List<Organization> orgs){
        Map<String,String> map = new HashMap<>();
        if(!CollectionUtil.isEmpty(orgs)){
            String orgIds = null;
            String orgTitle = null;
            for (Organization org : orgs) {
                if(StringUtil.isEmpty(orgIds)){
                    orgIds = org.getId().toString();
                }else {
                    orgIds = orgIds + ","+ org.getId();
                }
                if(StringUtil.isEmpty(orgTitle)){
                    orgTitle = org.getTitle();
                }else {
                    orgTitle = orgTitle + ","+org.getTitle();
                }
            }
            map.put("orgIds",orgIds);
            map.put("orgTitle",orgTitle);
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void disableRecoveryProjectUser(String ids, Long firmId, Long stationId, String activity, User headerUser) throws ArgumentErrorException {
        if(StringUtil.isEmpty(ids)){
            throw new ArgumentErrorException("请选择用户进行操作！");
        }
        String[] split = ids.split(",");
        if(split.length<=0){
            throw new ArgumentErrorException("请选择用户进行操作！");
        }
        List<Long> userIds = new ArrayList<>();
        for (String s : split) {
            userIds.add(Long.valueOf(s));
        }
        String remark = null;
        if("1".equals(activity)){
            remark = headerUser.getTitle()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"恢复";
        }else {
            remark = headerUser.getTitle()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"禁用";
        }
        if(firmId != null && stationId == null){
            userRepository.updateFirmUserActivity(userIds,firmId,activity,remark);
        }else if(firmId == null && stationId != null){
            userRepository.updateStationUserActivity(userIds,stationId,activity,remark);
        }

    }

    @Override
    public EmployeeUser getProjectUserById(Long id, Long firmId, Long stationId) {
        EmployeeUser user = new EmployeeUser();
        if(firmId != null && stationId == null){
            user = userDao.getFirmUserById(id,firmId);
        }else if(firmId == null && stationId != null){
            user =  userDao.getSationUserById(id,stationId);
        }
        if(user != null){
            findRoleAndOrg(null,user);
        }
        return user;
    }

    @Override
    public Page<EmployeeUser> getUserByStationIdOrFirmId(Long id, Long stationId, Long firmId, String keywords, PageParam pageParam) {
        Page<EmployeeUser> employeeUserPage = userDao.getUserByStationIdOrFirmId(id, stationId, firmId, keywords, pageParam);
        employeeUserPage.get().forEach(employeeUser -> {
                employeeUser.setStationId(stationId);
                employeeUser.setFirmId(firmId);
                findRoleAndOrg(null, employeeUser);}
        );
        return employeeUserPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void updateProjectUserById(Long id, Long firmId, Long stationId, String roleIds, String ascriptionOrgIds, String orgIds, String activity, User headerUser, BackUser headerBackUser, User user) throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        User userId = this.findByUserId(id);
        if(userId == null){
            throw new ArgumentErrorException("找不到id为"+id+"的用户！");
        }
        user.setItemsNumber(userId.getItemsNumber());
        //更新用户
        updateUser(user);
        if(StringUtil.isEmpty(roleIds)){
            throw new ArgumentErrorException("请选择对应项目的角色！");
        }
        String[] split = roleIds.split(",");
        if(split.length <= 0){
            throw new ArgumentErrorException("请选择对应项目的角色！");
        }
        if(StringUtil.isEmpty(ascriptionOrgIds)){
            throw new ArgumentErrorException("请选择对应项目的组织！");
        }
        List<Long> orgIdList = new ArrayList<>();
        if(!StringUtils.isEmpty(orgIds)){
            String[] orgIdArrays = orgIds.split(",");
            for (String s : orgIdArrays) {
                orgIdList.add(Long.valueOf(s));
            }
        }
        List<Long> roleList = new ArrayList<>();
        for (String s : split) {
            roleList.add(Long.valueOf(s));
        }

        List<Long> belongOrgIdList = new ArrayList<>();
        if(!StringUtils.isEmpty(ascriptionOrgIds)){
            String[] orgIdArrays = ascriptionOrgIds.split(",");
            for (String s : orgIdArrays) {
                belongOrgIdList.add(Long.valueOf(s));
            }
        }

        //解除用户之前绑定对应的项目的角色与组织
        if(stationId == null && firmId != null){
            //解绑
            userRepository.unbindFirmUserAndOrg(id,firmId);
            userRepository.unbindFirmUserAndRole(id,firmId);
            userRepository.unbindFirmUserAndSynergyOrg(id,firmId);
            //绑定组织
            //绑定协同组织
            if(!CollectionUtil.isEmpty(orgIdList)){
                for (Long orgId : orgIdList) {
                    userRepository.bindFirmOrg(id,firmId,orgId);
                }
            }
            //绑定归属组织
            for (Long ascriptionOrgId : belongOrgIdList) {
                userRepository.bindFirmAscriptionOrg(id,firmId, ascriptionOrgId);
            }
            userRepository.bindFirmRole(id,firmId,roleList);
        }else if(stationId != null && firmId == null){
            userRepository.unbindStationUserAndOrg(id,stationId);
            userRepository.unbindStationUserAndRole(id,stationId);
            userRepository.unbindStationUserAndSynergyOrg(id,stationId);
            //绑定组织
            //绑定协同组织
            if(!CollectionUtil.isEmpty(orgIdList)){
                for (Long orgId : orgIdList) {
                    userRepository.bindStaionOrg(id,stationId,orgId);
                }
            }
            //绑定归属组织
            for (Long ascriptionOrgId : belongOrgIdList) {
                userRepository.bindStaionAscriptionOrg(id,stationId, ascriptionOrgId);
            }
            userRepository.bindStationRole(id,stationId,roleList);
        }

        String remark = null;
        if(headerUser != null){
            if("1".equals(activity)){
                remark = headerUser.getTitle()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"恢复";
            }else {
                remark = headerUser.getTitle()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"禁用";
            }
        }else if(headerBackUser != null){
            if("1".equals(activity)){
                remark = headerBackUser.getTitle()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"恢复";
            }else {
                remark = headerBackUser.getTitle()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"禁用";
            }
        }

        if(firmId != null && stationId == null){
            userRepository.updateFirmUserActivity(Arrays.asList(id),firmId,activity,remark);
        }else if(firmId == null && stationId != null){
            userRepository.updateStationUserActivity(Arrays.asList(id),stationId,activity,remark);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void unbindProejctUser(String ids, Long firmId, Long stationId) throws ArgumentErrorException, ObjectNotFoundException, UniqueConstraintsException {
        if(StringUtil.isEmpty(ids)){
            throw new ArgumentErrorException("请选择用户进行操作");
        }
        String[] split = ids.split(",");
        if(split.length <= 0){
            throw new ArgumentErrorException("请选择用户进行操作");
        }
        for (String idStr : split) {
            unbindUser(Long.valueOf(idStr),stationId,firmId);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void addProjectUser(Long firmId, Long stationId, String ascriptionOrgIds, String orgIds, String roleIds, User user) throws ArgumentErrorException, ObjectNotFoundException, UniqueConstraintsException {
        if(user.getId() != null){
            User userId = findByUserId(user.getId());
            userId.setSex(user.getSex());
            userId.setTitle(user.getTitle());
            userId.setMail(user.getMail());
            userRepository.save(userId);
            bindProejctRoleOrg(user.getId(),firmId,stationId, ascriptionOrgIds, orgIds,roleIds);
        }else {
            //获取默认密码
            user.setPassword(MD5Util.encode(userProperties.getRootDefaultPassword(), SALT_V));
            //新增用户
            createUser(user,stationId,firmId, ascriptionOrgIds,orgIds,roleIds);
        }

    }

    @Override
    public void updateLastProejct(Long id, Long projectId, String projectFlag) {
        userRepository.updateLastProejct(id,projectId,projectFlag);
    }

    public static void main(String[] args) {
        System.out.println(MD5Util.encode(MD5Util.encode("ABcd1234",SALT_V),SALT_M));
    }

    @Override
    public List<UserProjectOrg> getUserByOrgAndRoleName(Long orgId, String roleName, Long stationId, Long firmId) {
        List<UserProjectOrg> result = new ArrayList<>();
        if(stationId != null && firmId == null){
            //List<Organization> organizations = orgService.findChildOrg(orgId,stationId);
            List<User> users = (List<User>) userRepository.getStationUserByOrgAndRoleName(orgId,roleName,stationId);
            if(!CollectionUtil.isEmpty(users)){
                for (User user : users) {
                    //查询当前用户在当前园区是否禁用
                    User user1 = userRepository.findByUserIdAndStationId(user.getId(),stationId);
                    if(user1!= null){
                        UserProjectOrg userProjectOrg = new UserProjectOrg();
                        userProjectOrg.setOrgId(orgId);
                        userProjectOrg.setUserId(user.getId());
                        userProjectOrg.setUserPhone(user.getPhone());
                        userProjectOrg.setUserTitle(user.getTitle());
                        result.add(userProjectOrg);
                    }
                }
            }
        }else if(firmId != null & stationId == null){
            //todo 目前没有单位账号 先不做逻辑处理
        }
        return result;
    }

    @Override
    public List<Map<String,Object>> getUserByStationIdAndOrg(List<Long> orgIds, String roleName, Long stationId) {
        List<Map<String,Object>> result = new ArrayList<>();
        for (Long orgId : orgIds) {
            List<UserProjectOrg> userProjectOrgs = getUserByOrgAndRoleName(orgId, roleName, stationId, null);
            if(!CollectionUtil.isEmpty(userProjectOrgs)){
                for (UserProjectOrg userProjectOrg : userProjectOrgs) {
                    Map<String,Object> map = new HashMap<>();
                    map.put("userId",userProjectOrg.getUserId());
                    map.put("userName",userProjectOrg.getUserTitle());
                    map.put("orgId",userProjectOrg.getOrgId());
                    result.add(map);
                }
            }
        }
        return result;
    }

    @Override
    public User updatePasswordByValidateCode(ChangePassword changePassword) throws UsernamePasswordException, ArgumentErrorException {
        //校验验证码是否正确
        String s = redisClient.get(changePassword.getPhone() + "-changePassword");
        if(!changePassword.getVerificationCode().equals(s)){
            throw new ArgumentErrorException("验证码不正确,请重新输入手机验证码!");
        }
        User user = userRepository.findByPhoneAndPassword(changePassword.getPhone(), MD5Util.encode(changePassword.getPassword(), SALT_M));
        if (user != null && user.getId().longValue() == changePassword.getId()) {
            User newUser = userRepository.updatePassword(changePassword.getId(), MD5Util.encode(changePassword.getNewPassword(), SALT_M));
            if (newUser != null) {
                logUtil.createLog(LogConsts.LOG_TYPE_CODE.ACTION, "修改密码", SystemConsts.ACTION.EDIT);
            }
            //重置密码第一次修改密码之后 清除重置密码标记
            redisClient.del(changePassword.getId() + "-resetPassword");
            //清除修改密码的key
            redisClient.del(changePassword.getId() + "-changePassword");
            return newUser;
        } else {
            throw new UsernamePasswordException("旧密码输入错误");
        }
    }

    @Override
    public User findByUserIdAndStationId(Long id, Long stationId) {
        return userRepository.findByUserIdAndStationId(id,stationId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void unbindUserAndRole(Long roleId, Long userId) {
        userRepository.unbindRole(userId,roleId);
    }

    @Override
    public User findByPhoneAndDecodePassword(String phone, String password) {
        return userRepository.findByPhoneAndPassword(phone,password);
    }

    @Override
    public List<Map<String, Object>> getUserByOrgId(Long orgId) throws ArgumentErrorException {
        List<Map<String, Object>> result = new ArrayList<>();
        String projectCode = ServerContextHolder.getContext().getProjectCode();
        if(StringUtil.isEmpty(projectCode)){
            throw new ArgumentErrorException("请选择对应项目进行操作");
        }
        List<UserProjectOrg> userProjectOrgs = getUserByOrgIdAndStationId(orgId, Long.valueOf(projectCode));
        if (!CollectionUtil.isEmpty(userProjectOrgs)) {
            for (UserProjectOrg userProjectOrg : userProjectOrgs) {
                Map<String, Object> map = new HashMap<>();
                map.put("userId", userProjectOrg.getUserId());
                map.put("userName", userProjectOrg.getUserTitle());
                map.put("orgId", userProjectOrg.getOrgId());
                result.add(map);
            }
        }

        return result;
    }

    @Override
    public void validateByWeChat(String phone, String type) throws ArgumentErrorException {
        Random random = new Random();
        try {
            String currentTimeStr = redisClient.get(phone + ":" + type + ":currentTime:weChat");
            if(!StringUtil.isEmpty(currentTimeStr)){
                Long currentTime = Long.parseLong(currentTimeStr);
                if((System.currentTimeMillis()-currentTime) <= 60*1000){
                    throw new ArgumentErrorException("该手机号已经1分钟之内发送过验证码！");
                }
            }
            String templateCode = "SMS_212560079";
            if("login".equals(type)){
                templateCode = "SMS_212560079";
            }else if("changePassword".equals(type)){
                templateCode = "SMS_212560076";
            }
            if(StringUtil.isEmpty(templateCode)){
                throw new ArgumentErrorException("暂无对应的短信模板！");
            }
            //第四次给出提示 获取验证码过于频繁，请5分钟后再试！
            String count = redisClient.get(phone + "-" + type + "count:weChat");
            if(!StringUtil.isEmpty(count) && Integer.valueOf(count)==4){
                throw new ArgumentErrorException("获取验证码过于频繁，请5分钟后再试！");
            }
            if(!StringUtil.isEmpty(count) && Integer.valueOf(count)==2){
                redisClient.set(phone + "-" + type + "count:weChat",String.valueOf(Integer.valueOf(count)+1),6*60);
            }else if(StringUtil.isEmpty(count) || "1".equals(count)){
                count = StringUtil.isEmpty(count)?"0":count;
                redisClient.set(phone + "-" + type + "count:weChat",String.valueOf(Integer.valueOf(count)+1),6*60);
            }else if(!StringUtil.isEmpty(count) && Integer.valueOf(count)==3){
                redisClient.set(phone + "-" + type + "count:weChat",String.valueOf(Integer.valueOf(count)+1),6*60);
            }
            Map<String, String> map = new HashMap<>();
            int code = random.nextInt(900000) + 100000;
            String validateCode = code + "";
            map.put("code", validateCode);
            String templateParam = "{\"code\":\"" + validateCode + "\"}";
            SmsUtil.sendSms(phone, map, templateCode, templateParam);
            redisClient.set(phone+"-"+type+":weChat", validateCode, 30*60);
            redisClient.set(phone + ":" + type + ":currentTime:weChat", String.valueOf(System.currentTimeMillis()),15*60);
        } catch (Exception e) {
            if(StringUtil.isEmpty(e.getMessage())){
                throw new ArgumentErrorException("获取验证码失败， 请重新获取！");
            }else {
                throw new ArgumentErrorException(e.getMessage());
            }

        }
    }

    @Override
    public String checkVerificationCode(String phone, String verificationCode) throws ArgumentErrorException {
        if(!"000000".equals(verificationCode)){
            String verificationCodeValues = redisClient.get(phone + "-changePassword:mob");
            if(StringUtil.isEmpty(verificationCodeValues)){
                throw new  ArgumentErrorException("未获取到该手机号的验证码！");
            }
            if(!verificationCode.equals(verificationCodeValues)){
                throw new ArgumentErrorException("验证码错误！");
            }
        }
        return "success";
    }

    @Override
    public void validateForMob(String phone, String type) throws ArgumentErrorException {
        Random random = new Random();
        try {
            //校验手机号是否存在
            User user = this.findByPhone(phone);
            if(user == null){
                throw new ArgumentErrorException("手机号不存在！");
            }
            String currentTimeStr = redisClient.get(phone + ":" + type + ":currentTime:mob");
            if(!StringUtil.isEmpty(currentTimeStr)){
                Long currentTime = Long.parseLong(currentTimeStr);
                if((System.currentTimeMillis()-currentTime) <= 60*1000){
                    throw new ArgumentErrorException("该手机号已经1分钟之内发送过验证码！");
                }
            }
            String templateCode = "SMS_212560079";
            if("login".equals(type)){
                templateCode = "SMS_212560079";
            }else if("changePassword".equals(type)){
                templateCode = "SMS_212560076";
            }
            if(StringUtil.isEmpty(templateCode)){
                throw new ArgumentErrorException("暂无对应的短信模板！");
            }
            //第四次给出提示 获取验证码过于频繁，请5分钟后再试！
            String count = redisClient.get(phone + "-" + type + "count:mob");
            if(!StringUtil.isEmpty(count) && Integer.valueOf(count)==4){
                throw new ArgumentErrorException("获取验证码过于频繁，请5分钟后再试！");
            }
            if(!StringUtil.isEmpty(count) && Integer.valueOf(count)==2){
                redisClient.set(phone + "-" + type + "count:mob",String.valueOf(Integer.valueOf(count)+1),6*60);
            }else if(StringUtil.isEmpty(count) || "1".equals(count)){
                count = StringUtil.isEmpty(count)?"0":count;
                redisClient.set(phone + "-" + type + "count:mob",String.valueOf(Integer.valueOf(count)+1),6*60);
            }else if(!StringUtil.isEmpty(count) && Integer.valueOf(count)==3){
                redisClient.set(phone + "-" + type + "count:mob",String.valueOf(Integer.valueOf(count)+1),6*60);
            }
            Map<String, String> map = new HashMap<>();
            int code = random.nextInt(900000) + 100000;
            String validateCode = code + "";
            map.put("code", validateCode);
            String templateParam = "{\"code\":\"" + validateCode + "\"}";
            SmsUtil.sendSms(phone, map, templateCode, templateParam);
            redisClient.set(phone+"-"+type+":mob", validateCode, 30*60);
            redisClient.set(phone + ":" + type + ":currentTime:mob", String.valueOf(System.currentTimeMillis()),30*60);
        } catch (Exception e) {
            if(StringUtil.isEmpty(e.getMessage())){
                throw new ArgumentErrorException("获取验证码失败， 请重新获取！");
            }else {
                throw new ArgumentErrorException(e.getMessage());
            }

        }
    }

    @Override
    public User findByPhoneAndVerificationCodeforMob(String phone, String verificationCode) throws ArgumentErrorException, UsernamePasswordException {
        if(!verificationCode.equals("000000")){
            String reult = redisClient.get(phone+"-"+"login:mob");
            if(StringUtil.isEmpty(reult)){
                throw new  ArgumentErrorException("验证码已失效");
            }
            if(!verificationCode.equals(reult)){
                throw new ArgumentErrorException("验证码输入错误");
            }
        }
        User user = userRepository.findByPhone(phone);
        checkUserByPhone(user);
        return user;
    }

    @Override
    public User changePasswordForMob(String phone, String verificationCode, String password) throws ArgumentErrorException {
        if("000000".equals(verificationCode)){
            User user = userRepository.findByPhone(phone);
            if(user != null){
                User newUser = userRepository.updatePassword(user.getId(), MD5Util.encode(password, SALT_M));
                if (newUser != null) {
                    logUtil.createLog(LogConsts.LOG_TYPE_CODE.ACTION, "修改密码", SystemConsts.ACTION.EDIT);
                }
                redisClient.del(phone+"-"+"changePassword:mob");
                return newUser;
            }else {
                throw new ArgumentErrorException("该手机号未注册用户，请重新输入手机号！");
            }
        }else {
            String reult = redisClient.get(phone+"-"+"changePassword:mob");
            if(StringUtil.isEmpty(reult)){
                throw new  ArgumentErrorException("验证码已失效");
            }
            if(verificationCode.equals(reult)){
                User user = userRepository.findByPhone(phone);
                if(user != null){
                    User newUser = userRepository.updatePassword(user.getId(), MD5Util.encode(password, SALT_M));
                    if (newUser != null) {
                        logUtil.createLog(LogConsts.LOG_TYPE_CODE.ACTION, "修改密码", SystemConsts.ACTION.EDIT);
                    }
                    redisClient.del(phone+"-"+"changePassword:mob");
                    return newUser;
                }else {
                    throw new ArgumentErrorException("该手机号未注册用户，请重新输入手机号！");
                }
            }else {
                throw new  ArgumentErrorException("验证码不正确，请重新输入");
            }
        }
    }

    @Override
    public List<User> findStationUserByStationId(Long stationId) {
        return userRepository.findStationUserByStationId(stationId);
    }

    @Override
    public List<UserProjectOrg> getUserByOrgIdAndStationId(Long orgId, Long stationId) {
        List<UserProjectOrg> result = new ArrayList<>();
        //查询归属组织
        List<User> users = userRepository.getUserByOrgIdAndStationId(orgId,stationId);
        if(!CollectionUtil.isEmpty(users)){
            for (User user : users) {
                //查询当前用户在当前园区是否禁用
                User user1 = userRepository.findByUserIdAndStationId(user.getId(),stationId);
                if(user1!= null){
                    UserProjectOrg userProjectOrg = new UserProjectOrg();
                    userProjectOrg.setOrgId(orgId);
                    userProjectOrg.setUserId(user.getId());
                    userProjectOrg.setUserPhone(user.getPhone());
                    userProjectOrg.setUserTitle(user.getTitle());
                    result.add(userProjectOrg);
                }
            }
        }
        //查询协同组织
        List<User> userList = userRepository.getUserBySynergyOrgIdAndStationId(orgId,stationId);
        if(!CollectionUtil.isEmpty(userList)){
            for (User user : userList) {
                //查询当前用户在当前园区是否禁用
                User user1 = userRepository.findByUserIdAndStationId(user.getId(),stationId);
                if(user1!= null){
                    UserProjectOrg userProjectOrg = new UserProjectOrg();
                    userProjectOrg.setOrgId(orgId);
                    userProjectOrg.setUserId(user.getId());
                    userProjectOrg.setUserPhone(user.getPhone());
                    userProjectOrg.setUserTitle(user.getTitle());
                    result.add(userProjectOrg);
                }
            }
        }
        return result;
    }

    @Override
    public User getLoginUserByPhone(String phone) throws ArgumentErrorException {
        User user = userRepository.findByPhone(phone);
        if(user == null){
            throw new ArgumentErrorException("手机号为："+phone+"不存在！");
        }
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void disableRecoveryProjectBackUser(String ids, Long firmId, Long stationId, String activity, BackUser headerBackUser) throws ArgumentErrorException {
        if(StringUtil.isEmpty(ids)){
            throw new ArgumentErrorException("请选择用户进行操作！");
        }
        String[] split = ids.split(",");
        if(split.length<=0){
            throw new ArgumentErrorException("请选择用户进行操作！");
        }
        List<Long> userIds = new ArrayList<>();
        for (String s : split) {
            userIds.add(Long.valueOf(s));
        }
        String remark = null;
        if("1".equals(activity)){
            remark = headerBackUser.getTitle()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"恢复";
        }else {
            remark = headerBackUser.getTitle()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"禁用";
        }
        if(firmId != null && stationId == null){
            userRepository.updateFirmUserActivity(userIds,firmId,activity,remark);
        }else if(firmId == null && stationId != null){
            userRepository.updateStationUserActivity(userIds,stationId,activity,remark);
        }
    }

    @Override
    public List<User> findStationUserByQueryCondition(String userName) throws ArgumentErrorException {
        String projectCode = ServerContextHolder.getContext().getProjectCode();
        if(StringUtil.isEmpty(projectCode)){
            throw new ArgumentErrorException("请选择项目进行操作！");
        }
        if(StringUtil.isEmpty(userName)){
            return findStationUserByStationId(Long.valueOf(projectCode));
        }else {
            userName = ".*"+userName+".*";
            return userRepository.findStationUserByQueryCondition(Long.valueOf(projectCode),userName);
        }
    }

}
